package com.app114.app.android.rk.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

import com.app114.app.android.rk.conf.Conf;
import com.app114.app.android.rk.log.Logger;

//----------------------------------------------------------------------------------------------------------------

/**
 * 
 * 
 */

public class FileUtil {

	private static final String TAG = FileUtil.class.getSimpleName();
	private static String v2c_folder_path;

	/**
	 * Read data from the InputStream
	 * 
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();
	}

	/**
	 * Sd card can be used to determine whether 2011-12-9 上午10:16:18
	 * 
	 * @return
	 */
	public static boolean createV2cFile() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			File file = new File(Environment.getExternalStorageDirectory(), Conf.FILE_NAME);
			if (!file.exists()) {
				file.mkdir();
			}
			v2c_folder_path = file.toString();
			return true;
		}
		return false;
	}

	public static String getV2cFilePath() {
		return v2c_folder_path = createV2cFile() ? v2c_folder_path : "";
	}

	/**
	 * 
	 * 2011-12-9 下午6:26:58
	 * 
	 * @param file
	 */
	public static void deleteFile(File file) {
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFile(files[i]);
				}
			}
			file.delete();
		} else {
			Logger.i(TAG, "delete File-->" + file.toString() + "is not exist");
		}
	}

	public static String savePic(Context context, Bitmap bitmap) throws IOException {
		String fileName = context.getCacheDir().getAbsolutePath() + System.currentTimeMillis() + ".png";

		FileOutputStream fos = new FileOutputStream(fileName);

		if (fos != null) {

			bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);

			fos.close();
		}
		return fileName;
	}

}
